//
//  SHHRegisterVC.swift
//  GoTravel
//
//  Created by lanou3g on 16/3/5.
//  Copyright © 2016年 SHH. All rights reserved.
//

import UIKit

class SHHRegisterVC: UIViewController {

    
    @IBOutlet weak var backImageView: UIImageView!
    
    @IBOutlet weak var userTextField: UITextField!
    
    @IBOutlet weak var passwordTextField: UITextField!
    
    @IBOutlet weak var passwordTextField2: UITextField!
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationItem.title = "注册"
        
        //背景图模糊效果
        let fixView = FXBlurView(frame: UIScreen.mainScreen().bounds)
        fixView.dynamic = false
        fixView.blurRadius = 15
        fixView.tintColor = UIColor.clearColor()
        self.backImageView.addSubview(fixView)
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.view.endEditing(true)
    }
    
    
    //注册按钮的点击事件
    @IBAction func registerAction(sender: AnyObject) {
        let alertController = UIAlertController(title: "温馨提示", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
        let defaultAction = UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: nil)
        let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
        
        if self.userTextField.text == "" || self.passwordTextField.text == "" || self.passwordTextField2.text == ""{
            alertController.message = "用户名或者密码不能为空"
            alertController.addAction(defaultAction)
            alertController.addAction(cancelAction)
            self.presentViewController(alertController, animated: true, completion: nil)
        }else if self.passwordTextField.text != self.passwordTextField2.text{
            alertController.message = "两次输入的密码不同，请重新输入"
            alertController.addAction(defaultAction)
            alertController.addAction(cancelAction)
            self.presentViewController(alertController, animated: true, completion: nil)
        }else{
            let user = AVUser()
            user.username = userTextField.text
            user.password = passwordTextField.text
            user.email = userTextField.text
            
            if self.isEmailType(user.email) {
                user.signUpInBackgroundWithBlock({ (succeeded:Bool, error:NSError!) -> Void in
                    
                    if succeeded {
                        let alertController = UIAlertController(title: "温馨提示", message: "注册成功", preferredStyle: UIAlertControllerStyle.Alert)
                        
//                        let defaultAction = UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: nil)
                        let defaultAction = UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: { (action:UIAlertAction) -> Void in
                            
                            let user = AVUser.currentUser()
                            if user == nil {
                                print("妹纸")
                            }else{
                                let query = AVQuery(className: "UserInfo")
                                print("我尼玛啊\(user["user_id"])")
                                query.whereKey("user_id", equalTo: user["user_id"])
                                let userArray = query.findObjects()
                                if userArray.isEmpty {
                                    print("空")
                                    let object = AVObject(className: "UserInfo")
                                    object.setObject(user.username, forKey: "name")
                                    object.saveInBackgroundWithBlock({ (succeeded:Bool, error:NSError!) -> Void in
                                        if succeeded {
                                            print("存储成功")
                                        }else{
                                            print("失败")
                                        }
                                    })
                                    
                                }else{
                                    print("不空")
                                }
                            }
                            
                            self.navigationController?.popViewControllerAnimated(true)
                        })
                        
                        alertController.addAction(defaultAction)
                        
                        self.presentViewController(alertController, animated: true, completion: nil)
                        
                        
                    }else{
                        print(error)
                        
                        let alertController = UIAlertController(title: "温馨提示", message: "注册失败", preferredStyle: UIAlertControllerStyle.Alert)
                        
                        let defaultAction = UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: nil)
                        
                        alertController.addAction(defaultAction)
                        
                        self.presentViewController(alertController, animated: true, completion: nil)

                    }
                    
                })
            }else{
                let alertController = UIAlertController(title: "温馨提示", message: "E-mail格式不正确", preferredStyle: UIAlertControllerStyle.Alert)
                let defaultAction = UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: nil)
                
                alertController.addAction(defaultAction)
                
//                self.navigationController?.popViewControllerAnimated(true)
                self.presentViewController(alertController, animated: true, completion: nil)
            }
            
        }
        
    }
    
    //判断是否是email
    func isEmailType(email:String)->Bool {
        let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
        let emailTest:NSPredicate = NSPredicate(format: "SELF MATCHES %@", emailRegex)
        return emailTest.evaluateWithObject(email)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
